package com.itheimamobileguard.activitys;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.mobile.R;
import com.itheimamobileguard.utils.StreamUtils;
import com.itheimamobileguard.utils.UIUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources.NotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.TextView;
import android.widget.Toast;

public class SplashActivity extends Activity {
	protected static final int SHOW_UPDATE = 1;
	protected static final int LOAD_MAINUI = 2;
	private TextView tv_splash_version;
	private TextView tv_info;
	// 包管理器
	private PackageManager packageManager;
	private int clientversionCode;
	private String desc;
	private String downloadurl;
	// 消息处理器
	public Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case LOAD_MAINUI:
				loadMainUI();
				break;
			case SHOW_UPDATE:
				AlertDialog.Builder builder = new Builder(SplashActivity.this);
				builder.setTitle("更新提醒");
				builder.setMessage(desc);
				builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
					
					@Override
					public void onCancel(DialogInterface dialog) {
						loadMainUI();
					}
				});
				
				builder.setNegativeButton("下次再说", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						loadMainUI();
					}
				});

				builder.setPositiveButton("立刻更新", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						System.out.println("正在下载"+downloadurl);
						download(downloadurl);
					}
				});
				builder.show();
				break;
			}
		}
	};
	
	
	/**
	 *显示主界面 
	 */
	private void loadMainUI() {
		Intent intent = new Intent(SplashActivity.this, HomeActivity.class);
		startActivity(intent);
		finish();
	};
	
	/**
	 * 多线程下载
	 * @param downloadurl
	 */
	private void download(String downloadurl) {
		HttpUtils http = new HttpUtils();
		http.download(downloadurl, "/mnt/sdcard/mobile.apk", new RequestCallBack<File>() {
			
			@Override
			public void onSuccess(ResponseInfo<File> arg0) {
				Intent intent = new Intent();
				intent.setAction("android.intent.action.VIEW");
				intent.addCategory("android.intent.category.DEFAULT");
				
				//intent.setType("application/vnd.android.package-archive");
				//intent.setData(Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"temp.apk")));
				intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"mobile.apk")), 
						"application/vnd.android.package-archive");
				startActivityForResult(intent, 0);
			}
			
			@Override
			public void onFailure(HttpException arg0, String arg1) {
				Toast.makeText(SplashActivity.this, "下载失败", 0).show();
				System.out.println(arg1);
				arg0.printStackTrace();
				loadMainUI();
			}

			@Override
			public void onLoading(long total, long current, boolean isUploading) {
				tv_info.setText(current+"/"+total);
				super.onLoading(total, current, isUploading);
			}
			
		});
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		loadMainUI();
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		tv_splash_version = (TextView) findViewById(R.id.tv_splash_version);
		tv_info = (TextView) findViewById(R.id.tv_info);
		packageManager = getPackageManager();
		try {
			PackageInfo packInfo = packageManager.getPackageInfo(
					getPackageName(), 0);
			String version = packInfo.versionName;
			clientversionCode = packInfo.versionCode;
			tv_splash_version.setText(version);
			checkVersion();
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			// 不会发生 can't reach
		}

	}

	/**
	 * 链接服务器，检测是否存在新的版本
	 */
	private void checkVersion() {
		new Thread() {
			public void run() {
				Message msg = Message.obtain();
				// 检查代码的执行时间
				long startTime = System.currentTimeMillis();

				try {
					URL url = new URL(getResources().getString(
							R.string.serverUrl));
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.setRequestMethod("GET");
					conn.setConnectTimeout(5000);
					int code = conn.getResponseCode();
					if (code == 200) {
						InputStream is = conn.getInputStream();// json文本
						String json = StreamUtils.readStream(is);
						if (TextUtils.isEmpty(json)) {
							// 获取json失败
							UIUtils.showToast(SplashActivity.this,
									"错误2016，json获取失败，请联系客服");
						} else {
							JSONObject jsonObject = new JSONObject(json);
							downloadurl = jsonObject.getString("downloadurl");
							int serverVersion = jsonObject.getInt("verison");
							desc = jsonObject.getString("desc");
							if (clientversionCode == serverVersion) {
								// 相同，进入应用程序主界面
								msg.what = LOAD_MAINUI;
							} else {
								// 不同，弹出更新提醒对话框
								msg.what = SHOW_UPDATE;
							}
						}
					} else {
						UIUtils.showToast(SplashActivity.this,
								"错误2015，服务器状态码获取失败，请联系客服");
						msg.what = LOAD_MAINUI;
					}
				} catch (MalformedURLException e) {
					e.printStackTrace();
					UIUtils.showToast(SplashActivity.this,
							"错误2014，url路径不正确，请联系客服");
					msg.what = LOAD_MAINUI;
				} catch (NotFoundException e) {
					e.printStackTrace();
					UIUtils.showToast(SplashActivity.this,
							"错误2013，服务器地址找不到，请联系客服");
					msg.what = LOAD_MAINUI;
				} catch (IOException e) {
					e.printStackTrace();
					UIUtils.showToast(SplashActivity.this, "错误2012，网络异常，请联系客服");
					msg.what = LOAD_MAINUI;
				} catch (JSONException e) {
					e.printStackTrace();
					UIUtils.showToast(SplashActivity.this,
							"错误2011，json解析异常，请联系客服");
					msg.what = LOAD_MAINUI;
				} finally {
					long endTime = System.currentTimeMillis();
					long dTime = endTime - startTime;
					if (dTime > 2000) {
						handler.sendMessage(msg);
					} else {
						try {
							Thread.sleep(2000 - dTime);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						handler.sendMessage(msg);
					}
				}
			}

		}.start();
	}

}
